package csc.com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="Login", urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = 919387497383327444L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		String errorMsg = null;
		if (userName == null || userName.equals("")) {
			errorMsg = "Please enter your user name";
		}
		if (password == null || password.equals("")) {
			errorMsg = "Please enter your password";
		}
		if ((userName == null || userName.equals("")) && (password == null || password.equals(""))) {
			errorMsg = "Please enter your user name and password";
		}
		if (errorMsg != null ) {
			RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/login.html");
			PrintWriter out = resp.getWriter();
			out.println("<font color=red>"+errorMsg+"</font>");
			requestDispatcher.include(req, resp);
		} else {
			Connection connection = (Connection) getServletContext().getAttribute("DBConnection");
			PreparedStatement preparedStatement = null;
			ResultSet resultSet = null;
			try {
				
				preparedStatement = connection.prepareStatement("select username, password, address, email, countlogin from Users where username=? and password=? limit 1");
				preparedStatement.setString(1, userName);
				preparedStatement.setString(2, password);
				resultSet = preparedStatement.executeQuery();
				
				if (resultSet.next()) {
					int count = resultSet.getInt("countLogin");
					if (count == 0) {
						countLogin(count + 1,  resultSet.getString("username"));
						RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/loginSuccess.html");
		                PrintWriter out= resp.getWriter();
		                out.println("<font color=blue font-size=14>Hello ,"+ resultSet.getString("username") + " First login you should change your password" +"</font>");
		                out.println("<form action='changePassword' method='post'>"+ 
		                		"<table><tr><td>User name</td><td>"+ resultSet.getString("username") + "</td>" +
		                		"<input type='hidden' name='username' value='"+ resultSet.getString("username") +"'></tr>"
		                		+ "<tr><td>New Password</td><td><input type='password' name='password'></td></tr>"
		                		+"<tr><td></td><td><input type='submit' value='Change'></td></tr>"
		                		+ "</table>" +	
		                		"</form>" );
		                requestDispatcher.include(req, resp);
					} else {
						countLogin(count + 1,  resultSet.getString("username"));
						RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/loginSuccess.html");
		                PrintWriter out= resp.getWriter();
		                out.println("<font color=green>Hello ," + resultSet.getString("username") +"</font>");
		                requestDispatcher.include(req, resp);
					}
	                
				} else {
					RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/login.html");
	                PrintWriter out= resp.getWriter();
	                out.println("<font color=red>The username or password you entered is incorrect.</font>");
	                requestDispatcher.include(req, resp);
					
				}
			
			} catch (SQLException e) {
				e.printStackTrace();
				throw new ServletException("DB Connection problem.");
			} finally {
				try {
					resultSet.close();
					preparedStatement.close();
				} catch (SQLException e) {
					
				}
			}
		}
	}

	public void countLogin(int count, String user) throws ServletException {
		Connection con = (Connection) getServletContext().getAttribute("DBConnection");
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement("update usermanagement.users set countlogin='"+ count + "' where username='" + user + "'");
			ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServletException("DB Connection problem.");
		} finally {
			try {
				ps.close();
			} catch (SQLException e) {
			}
		}
	}

}
